<template>
  <div>
    <section class="todoapp">
      <!-- header -->
      <header class="header">
        <h1>todos</h1>
        <input
          class="new-todo"
          autofocus
          autocomplete="off"
          placeholder="What needs to be done?"
          @keyup.enter="addTodo"
        >
      </header>

      <!-- section -->
      <section
        class="main"
        v-show="todos.length"
      >
        <input
          class="toggle-all"
          id="toggle-all"
          type="checkbox"
          :checked="allChecked"
          @change="toggleAll(!allChecked)"
        >
        <label for="toggle-all"></label>
        <ul class="todo-list">
          <TodoItem
            name="Todo"
            v-for="(todo,index) in filterTodo"
            :key="index"
            :todo="todo"
          />
        </ul>
      </section>

      <!-- footer -->
      <footer
        class="footer"
        v-show="todos.length"
      >
        <span class="todo-count">
          <strong>{{ remaining }}</strong>
          {{ remaining | pluralize('item') }} left
        </span>
        <ul class="filters">
          <li
            v-for="(v,i) in filters"
            :key="i"
          >
            <a
              :href="'#/'+i"
              :class="{selected: visibility === i}"
              @click="visibility = i"
            >{{ i | capitalize }}</a>
          </li>
        </ul>
        <button
          class="clear-completed"
          v-show="todos.length > remaining"
          @click="clearCompleted"
        >
          Clear completed
        </button>
      </footer>
    </section>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import TodoItem from "./TodoItem";

let filterObj = {
  all: (todos) => todos,
  active: (todos) => todos.filter((todo) => !todo.done),
  completed: (todos) => todos.filter((todo) => todo.done),
};

export default {
  data() {
    return {
      visibility: "all",
      filters: filterObj,
    };
  },
  created() {},
  methods: {
    ...mapActions(["toggleAll", "clearCompleted"]),
    addTodo(e) {
      let text = e.target.value;
      if (text.trim()) {
        this.$store.dispatch("addTodo", text);
      }
      e.target.value = "";
    },
  },
  computed: {
    todos() {
      return this.$store.state.todos;
    },
    filterTodo() {
      return this.filters[this.visibility](this.todos);
    },
    remaining() {
      return this.todos.filter((todo) => !todo.done).length;
    },
    allChecked() {
      return this.todos.every((todo) => todo.done);
    },
  },
  filters: {
    pluralize: (n, v) => (n === 1 ? v : v + "s"),
    capitalize: (v) => v.charAt(0).toUpperCase() + v.slice(1),
  },
  components: {
    TodoItem,
  },
};
</script>

<style src="../todolist/css/main.css"></style>
<style scoped>
</style>